<template>
  <div>
    <BasicTable
      @register="registerTable"
      :title="mode == 'todolistExecute' || mode == 'todolistConfirm' ? '我的待办' : '任务列表'"
      :api="mode == 'todolistExecute' || mode == 'todolistConfirm' ? queryTodoTask : queryTasks"
      :loading="true"
      :scroll="{ x: false, y: 'calc(100vh - 350px)' }"
    >
      <template #form-tm="{ model, field }">
        <a-radio-group
          v-model:value="choosetmType"
          style="margin: 0 5px 5px 0"
          button-style="solid"
          @change="changeChooseTm"
        >
          <a-radio-button value="1">本月</a-radio-button>
          <a-radio-button value="2">下个月</a-radio-button>
          <a-radio-button value="3">本季度</a-radio-button>
          <a-radio-button value="4">本年</a-radio-button>
          <a-radio-button value="5">自定义</a-radio-button>
        </a-radio-group>
        <a-range-picker
          v-show="choosetmType == '5'"
          v-model:value="model[field]"
          valueFormat="YYYY-MM-DD"
          :allowClear="false"
        />
      </template>
      <template #itemname="{ record }">
        <div style="text-align: left" @click="onViewExecuteRecordButtonClick(record)">{{
          record.itemname
        }}</div>
      </template>
      <template #plantm="{ record }">
        <div>
          <a-tag
            color="#cd201f"
            v-if="
              record.hasfinish === false &&
              record.hasend === false &&
              moment(record.planendtm).isBefore(moment().format('YYYY-MM-DD HH:mm:ss'))
            "
          >
            已超时</a-tag
          >
          <a-tag
            color="#f50"
            v-else-if="
              record.hasfinish === false &&
              record.hasend === false &&
              moment(record.planendtm).diff(moment().format('YYYY-MM-DD HH:mm:ss'), 'day') <= 7
            "
            >即将超时</a-tag
          >
          {{
            moment(record.planbegintm).format('YYYY-MM-DD') +
            '~' +
            moment(record.planendtm).format('YYYY-MM-DD')
          }}
        </div>
      </template>
      <template #catname="{ record }">
        <Icon
          color="#1677ffbf"
          style="font-size: 15px"
          :icon="
            taskTypeOptions.filter((item) => item.label == record.catname)[0]?.icon ??
            'ant-design:safety-certificate-outlined'
          "
        ></Icon>
        {{ record.catname }}
      </template>
      <template #status="{ record, text, column }">
        <a-tag v-if="record.hasend === true" color="red">终止取消</a-tag>
        <a-tag v-else-if="record.hasfinish === true" color="green">已完成</a-tag>
        <a-tag v-else-if="record.hasfinish === false" color="orange">执行中</a-tag>
      </template>
      <template #transInfo="{ record }">
        <div style="display: flex; flex-wrap: nowrap; justify-content: center">
          <div class="transInfo">
            <div>
              <span v-if="record?.transdeptid <= 0 || record?.transdeptid === record.resdeptid">{{
                record.resdeptname
              }}</span>
              <span v-else-if="record?.transdeptid > 0 && record?.transdeptid !== record.resdeptid"
                >{{ record.resdeptname }}→{{ record.transdeptname }}</span
              >
            </div>

            <div>
              <span
                v-if="
                  record?.transuserid === null ||
                  record?.transuserid === 0 ||
                  record?.transuserid === record.resuserid1 ||
                  record?.transuserid === record.resuserid2
                "
                >{{
                  (record.resusername1 ?? '') +
                  (record.resuserid2 !== null && record.resuserid2 !== 0 && record.resusername2
                    ? ',' + record.resusername2
                    : '')
                }}</span
              >
              <span
                v-else-if="
                  record?.transuserid !== null &&
                  record?.transuserid > 0 &&
                  record?.transuserid !== record.resuserid2 &&
                  record?.transuserid !== record.resuserid1
                "
                >{{
                  (record.resusername1 ?? '') +
                  (record.resuserid2 !== null && record.resuserid2 !== 0 && record.resusername2
                    ? ',' + record.resusername2
                    : '')
                }}→{{ record.transusername ?? '' }}</span
              >
            </div>
          </div>
          <div class="transState">
            <a-tag
              v-if="
                (record.transdeptid !== 0 || record.transuserid !== 0) &&
                record.transhasreceive === false &&
                !record.transreceivetm
              "
              >未接收</a-tag
            >
            <a-tag
              color="success"
              v-else-if="
                (record.transdeptid !== 0 || record.transuserid !== 0) &&
                record.transhasreceive === true &&
                record.transreceivetm
              "
              >已接收</a-tag
            >
            <a-tag
              color="error"
              v-else-if="
                (record.transdeptid !== 0 || record.transuserid !== 0) &&
                record.transhasreceive === false &&
                record.transreceivetm
              "
              >已拒收</a-tag
            >
          </div>
        </div>
        <!-- 如当前责任部门为空或当前责任部门与责任部门相同时，显示责任部门名称； -->
        <!-- 如当前责任部门不为空切与责任部门不同时，显示为：责任部门名称→当前责任部门； -->
      </template>
      <template #action="{ record }">
        <!-- 当record.istransreceiver === true时，表示当前用户为转交接受部门/人 -->
        <TableAction
          v-if="record.istransreceiver === true"
          :actions="[
            {
              icon: 'ant-design:file-search-outlined',
              onClick: onViewTaskInfoButtonClick.bind(null, record),
              tooltip: '查看任务',
            },
            {
              tooltip: '报告',
              icon: 'ant-design:file-text-outlined',
              color: 'success',
              onClick: onRecordButtonClick.bind(null, record),
            },
            {
              icon: 'ant-design:carry-out-filled',
              tooltip: '接收',
              color: 'success',
              ifShow:
                record.transhasreceive === false &&
                (mode == 'todolistExecute' || mode == 'alllistExecute'),
              popConfirm: {
                title: '是否确认接收任务',
                placement: 'left',
                confirm: onReceiveTaskItemButtonClick.bind(null, record),
              },
            },
            {
              icon: 'ant-design:close-square-filled',
              tooltip: '拒收',
              color: 'error',
              ifShow:
                record.transhasreceive === false &&
                (mode == 'todolistExecute' || mode == 'alllistExecute'),
              popConfirm: {
                title: '是否确认拒收任务',
                placement: 'left',
                confirm: onRefuseTaskItemButtonClick.bind(null, record),
              },
            },
            {
              icon: 'ant-design:rollback-outlined',
              tooltip: '退回',
              color: 'warning',
              ifShow:
                record.transhasreceive === true &&
                (mode == 'todolistExecute' || mode == 'alllistExecute'),
              popConfirm: {
                title: '是否确认退回任务',
                placement: 'left',
                confirm: onReturnTaskItemButtonClick.bind(null, record),
              },
            },
          ]"
        />
        <!-- 当record.istransreceiver === false时，表示当前用户为任务责任部门/负责人 -->
        <TableAction
          v-else-if="record.istransreceiver === false"
          :actions="[
            {
              icon: 'ant-design:file-search-outlined',
              onClick: onViewTaskInfoButtonClick.bind(null, record),
              tooltip: '查看任务',
            },
            {
              tooltip: '报告',
              icon: 'ant-design:file-text-outlined',
              color: 'success',
              onClick: onRecordButtonClick.bind(null, record),
            },
            {
              icon: 'ant-design:swap-outlined',
              tooltip: '转交',
              color: 'success',
              ifShow:
                ((record.transdeptid == 0 && record.transuserid == 0) ||
                  ((record.transdeptid !== 0 || record.transuserid !== 0) &&
                    record.transhasreceive === false)) &&
                (mode == 'todolistExecute' || mode == 'alllistExecute'),
              popConfirm: {
                title: '是否确认转交任务',
                placement: 'left',
                confirm: onDispatchTaskItemButtonClick.bind(null, record),
              },
            },
            {
              icon: 'ant-design:stop-outlined',
              tooltip: '取消转交',
              color: 'error',
              ifShow:
                (record.transdeptid !== 0 || record.transuserid !== 0) &&
                record.transhasreceive === false &&
                !record.transreceivetm &&
                (mode == 'todolistExecute' || mode == 'alllistExecute'),
              popConfirm: {
                title: '是否确认取消转交任务',
                placement: 'left',
                confirm: onCancelTaskItemButtonClick.bind(null, record),
              },
            },
            {
              icon: 'ant-design:close-circle-outlined',
              color: 'error',
              tooltip: '终止',
              ifShow:
                record.hasend === false &&
                record.hasfinish === false &&
                (mode == 'todolistExecute' || mode == 'alllistExecute'),
              popConfirm: {
                title: '是否确认终止任务项',
                placement: 'left',
                confirm: onEndTaskItemButtonClick.bind(null, record),
              },
            },
            {
              tooltip: '继续',
              color: 'success',
              icon: 'ant-design:play-circle-outlined',
              ifShow:
                record.hasend === true && (mode == 'todolistExecute' || mode == 'alllistExecute'),
              popConfirm: {
                title: '是否确认继续任务项',
                placement: 'left',
                confirm: onContinueTaskItemButtonClick.bind(null, record),
              },
            },
            {
              icon: 'ant-design:carry-out-outlined',
              tooltip: '完成',
              color: 'success',
              ifShow:
                record.hasfinish === false &&
                record.hasend === false &&
                (mode == 'todolistExecute' || mode == 'alllistExecute'),
              popConfirm: {
                title: '是否确认完成任务',
                placement: 'left',
                confirm: onFinishTaskItemButtonClick.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <ExecuteRecordDrawer
      @register="registerExecuteRecordDrawer"
      @success="opSuccess"
      :mode="mode"
      :orgcode="searchInfo.orgcode"
    />
    <!-- <AddOrUpdateExecuteRecord
      @register="registerAddOrUpdateExecuteRecordModal"
      @success="opSuccess"
    /> -->
    <TaskInfoDrawer
      :orgcode="searchInfo.orgcode"
      @register="registerTaskInfoDrawer"
      @success="opSuccess"
      mode="onlyInfo"
    />
    <TransmitTaskItemModal
      :orgcode="searchInfo.orgcode"
      @register="registerTransmitTaskItemModal"
      @success="opSuccess"
    />
  </div>
</template>
<script lang="ts">
  import { defineComponent, watch, unref, computed, ref, onMounted, onBeforeMount } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { Tag } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import { getUserOrganization } from '/@/api/ehs/organization';
  //使用modal弹出窗口
  import { useModal } from '/@/components/Modal';
  import { useDrawer } from '/@/components/Drawer';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { getAllTaskCategory } from '/@/api/ehs/taskCategory';
  import { queryEnumOption } from '/@/api/qms/exchangeData';
  import { useGlobSetting } from '/@/hooks/setting';
  import { reportEhsTask } from '/@/api/ehs/taskItem';
  const { globalProjectCode } = useGlobSetting();
  import { getFileApi } from '/@/api/platform/file';
  import * as XLSX from 'xlsx';
  import { Icon } from '/@/components/Icon';
  import moment from 'moment';
  import { queryTodoTask, queryTasks } from '/@/api/ehs/taskBench';
  import { userTodoTaskListConditionSchema, todoTaskListColumns } from './taskBench.data';
  import { useRoute } from 'vue-router';
  import ExecuteRecordDrawer from './ExecuteRecordDrawer.vue';
  const { uploadUrl } = useGlobSetting();
  import {
    finishItem,
    endItem,
    continueItem,
    cancelTransmit,
    fulfillTransmit,
    rejectTransmit,
    returnTransmit,
  } from '/@/api/ehs/taskItem';
  import TaskInfoDrawer from '../taskConsole/TaskInfoDrawer.vue';
  // import AddOrUpdateExecuteRecord from './AddOrUpdateExecuteRecord.vue';
  import TransmitTaskItemModal from './TransmitTaskItemModal.vue';
  export default defineComponent({
    name: 'taskBnechIndex',
    components: {
      BasicTable,
      TableAction,
      Tag,
      Icon,
      ExecuteRecordDrawer,
      TaskInfoDrawer,
      TransmitTaskItemModal,
      // AddOrUpdateExecuteRecord,
    },
    setup(props, {}) {
      const route = useRoute();
      const mode = ref('');
      const projectCode = ref<String>(globalProjectCode);
      const searchInfo = ref({
        orgcode: '',
      });
      const choosetmType = ref('1');
      const taskTypeOptions = ref([]);
      // const [
      //   registerAddOrUpdateExecuteRecordModal,
      //   { openModal: openAddOrUpdateExecuteRecordModal },
      // ] = useModal();
      const [registerTaskInfoDrawer, { openDrawer: openTaskInfoDrawer }] = useDrawer();
      const [registerExecuteRecordDrawer, { openDrawer: openExecuteRecordDrawer }] = useDrawer();
      const [registerTransmitTaskItemModal, { openModal: openTransmitTaskItemModal }] = useModal();
      const [registerTable, { reload, getForm }] = useTable({
        columns: todoTaskListColumns, //表头数据
        formConfig: {
          actionColOptions: {
            span: 3,
          },
          fieldMapToTime: [
            ['tm', ['begintm', 'endtm'], 'YYYY-MM-DD'],
            // 支持多个字段
          ],
          labelWidth: 80, //设置查询表单中label的宽度
          schemas: userTodoTaskListConditionSchema, // form查询表单
          showResetButton: false, //查询条件部分中是否显示重置按钮
        },
        immediate: false,
        beforeFetch: (params) => {
          params.orgcode = searchInfo.value.orgcode;
          params.flag = params.flag ?? 2;
          return params;
        },
        afterFetch: (data) => {
          return data.items;
        },
        useSearchForm: true,
        showTableSetting: true, //是否显示表格设置
        showIndexColumn: true,
        canResize: true,
        bordered: true,
        striped: false,
        actionColumn: {
          width:
            route.fullPath.split('/')[3] == 'todolistExecute' ||
            route.fullPath.split('/')[3] == 'alllistExecute'
              ? 250
              : 80,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
        pagination: true,
      });

      function opSuccess() {
        reload();
      }

      // function tdClassName(record) {
      //   if (record.status == 1 || record.status == 2) {
      //     if (moment(record.planendtm).isBefore(moment().format('YYYY-MM-DD HH:mm:ss'))) {
      //       return 'dangerRow';
      //     } else if (
      //       moment(record.planendtm).diff(moment().format('YYYY-MM-DD HH:mm:ss'), 'day') <= 7
      //     ) {
      //       return 'warningRow';
      //     } else return 'normalRow';
      //   }
      // }

      function changeChooseTm(e) {
        let op = {
          1: [
            moment().startOf('month').format('YYYY-MM-DD'),
            moment().endOf('month').format('YYYY-MM-DD'),
          ],
          2: [
            moment().subtract(-1, 'month').startOf('month').format('YYYY-MM-DD'),
            moment().subtract(-1, 'month').endOf('month').format('YYYY-MM-DD'),
          ],
          3: [
            moment().startOf('quarter').format('YYYY-MM-DD'),
            moment().endOf('quarter').format('YYYY-MM-DD'),
          ],
          4: [
            moment().startOf('year').format('YYYY-MM-DD'),
            moment().endOf('year').format('YYYY-MM-DD'),
          ],
        };
        if (e.target.value != '5') {
          getForm().setFieldsValue({
            tm: op[e.target.value],
          });
        }
        getForm().clearValidate();
      }

      function onViewTaskInfoButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '任务信息',
          operateString: record.itemname,
          dataId: record.taskid,
        };
        openTaskInfoDrawer(true, propsData);
      }

      /**
       * 完成任务项
       */
      function onFinishTaskItemButtonClick(record) {
        finishItem(record.itemid).then((res) => {
          if (!res) {
            createMessage.success('任务项完成成功');
            opSuccess();
          } else {
            createMessage.error('任务项完成失败');
          }
        });
      }

      /**
       * 终止任务项
       */
      function onEndTaskItemButtonClick(record) {
        endItem(record.itemid).then((res) => {
          if (!res) {
            createMessage.success('任务项终止成功');
            opSuccess();
          } else {
            createMessage.error('任务项终止失败');
          }
        });
      }

      /**
       * 继续任务项
       */
      function onContinueTaskItemButtonClick(record) {
        continueItem(record.itemid).then((res) => {
          if (!res) {
            createMessage.success('任务项继续成功');
            opSuccess();
          } else {
            createMessage.error('任务项继续失败');
          }
        });
      }

      /**
       * 转交任务项
       */
      function onDispatchTaskItemButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '任务项',
          operateString: '转交',
          dataId: record.itemid,
        };
        openTransmitTaskItemModal(true, propsData);
      }

      /**
       *
       * 接收转交给自己的任务
       */
      function onReceiveTaskItemButtonClick(record) {
        fulfillTransmit(record.itemid).then((res) => {
          if (!res) {
            createMessage.success('任务项接收成功');
            opSuccess();
          } else {
            createMessage.error('任务项接收失败');
          }
        });
      }

      /**
       *
       * 取消转交
       */
      function onCancelTaskItemButtonClick(record) {
        cancelTransmit(record.itemid).then((res) => {
          if (!res) {
            createMessage.success('任务项取消转交成功');
            opSuccess();
          } else {
            createMessage.error('任务项取消转交失败');
          }
        });
      }

      /**
       *
       * 拒收任务项
       */
      function onRefuseTaskItemButtonClick(record) {
        rejectTransmit(record.itemid).then((res) => {
          if (!res) {
            createMessage.success('任务项拒收成功');
            opSuccess();
          } else {
            createMessage.error('任务项拒收失败');
          }
        });
      }

      /**
       *
       * 退回任务项
       */
      function onReturnTaskItemButtonClick(record) {
        returnTransmit(record.itemid).then((res) => {
          if (!res) {
            createMessage.success('任务项退回成功');
            opSuccess();
          } else {
            createMessage.error('任务项退回失败');
          }
        });
      }

      function openReport(id) {
        window.open(uploadUrl + getFileApi + id);
      }
      function onRecordButtonClick(record) {
        if (record.rptid <= 0) {
          reportEhsTask(record.itemid).then((res) => {
            if (res) {
              createMessage.success('重新生成报告成功');
              openReport(res);
            } else {
              createMessage.error('重新生成报告失败');
            }
          });
        } else {
          openReport(record.rptid);
        }
      }

      //查看执行记录
      function onViewExecuteRecordButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '任务执行记录',
          operateString: record.itemname + (record.unitname ?? ''),
          itemid: record.itemid,
          groupid: record.groupid,
          itemRecord: record,
          hasOperate: record.hasfinish === false && record.hasend === false,
        };
        openExecuteRecordDrawer(true, propsData);
      }

      /**
       *  新增执行记录(填写执行记录)
       */
      // function onAddExecuteRecordButtonClick(record) {
      //   let propsData: QcUnifyTransToChildProps = {
      //     moduleName: '任务执行记录',
      //     operateType: OperationTypeEnum.ADD,
      //     taskItemRecord: record,
      //   };
      //   openAddOrUpdateExecuteRecordModal(true, propsData);
      // }

      onMounted(() => {
        console.log(route.fullPath.split('/')[3], 'full');
        mode.value = route.fullPath.split('/')[3];
        console.log(mode.value, 'mode');
        getForm().updateSchema({
          field: 'flag',
          ifShow: mode.value == 'todolistExecute' || mode.value == 'todolistConfirm' ? false : true,
        });
        // 需要传入用户有效组织
        getUserOrganization(projectCode.value).then((res) => {
          searchInfo.value.orgcode = res ? res.orgcode : null;
          getAllTaskCategory(res.orgcode).then((res3) => {
            taskTypeOptions.value = res3
              ? res3?.map((option) => {
                  return {
                    label: option.catname,
                    value: option.catcode,
                    icon: option.icon,
                  };
                })
              : [];
            reload();
          });
        });
      });

      return {
        moment,
        mode,
        opSuccess,
        taskTypeOptions,
        registerTable,
        registerTaskInfoDrawer,
        registerExecuteRecordDrawer,
        registerTransmitTaskItemModal,
        onViewTaskInfoButtonClick,
        // registerAddOrUpdateExecuteRecordModal,
        searchInfo,
        // tdClassName,
        choosetmType,
        changeChooseTm,
        onFinishTaskItemButtonClick,
        onEndTaskItemButtonClick,
        onContinueTaskItemButtonClick,
        onDispatchTaskItemButtonClick,
        onViewExecuteRecordButtonClick,
        queryTodoTask,
        queryTasks,
        onReceiveTaskItemButtonClick,
        onCancelTaskItemButtonClick,
        onRefuseTaskItemButtonClick,
        onReturnTaskItemButtonClick,
        onRecordButtonClick,
        // onAddExecuteRecordButtonClick,
      };
    },
  });
</script>
<style scoped>
  a {
    color: black;
  }
  a:hover {
    color: #217cc2;
  }
  .dangerRow {
    color: rgb(195, 5, 5);
  }
  .warningRow {
    color: rgb(224, 78, 6);
  }
  .transState {
    margin-left: 5px;
  }
</style>
